import { Component } from "@angular/core";
import {Events,ModalController,NavController,NavParams} from "ionic-angular";
import { QRScanner, QRScannerStatus } from "@ionic-native/qr-scanner";
import {EleDetailPage} from "../../elevator-detail/elevator-detail";
import { Geolocation } from "@ionic-native/geolocation";
import {HttpService} from "../../../providers/http.service";
import {CheckElevator} from "../checkElevator";

@Component({
  selector: "check-elevator-scan",
  templateUrl: "check-elevator-scan.html",
  providers: [HttpService]
})
export class CheckElevatorScan{
  workType: string;
  lightActive: boolean = false;
  cameraToggleActive: boolean = false;
  // 定义设备Id
  public implementObjectId:any;
  // 定义计划Id
  public planId:any;

  constructor(
    private navCtrl: NavController,
    private events: Events,
    private modalCtrl: ModalController,
    private navParams: NavParams,
    private qrScanner: QRScanner,
    private geolocation: Geolocation,
    private httpService: HttpService
  ) {
    this.workType = this.navParams.get("workType");
    this.implementObjectId = this.navParams.get("implementObjectId");
    this.planId = this.navParams.get("planId");

    this.events.subscribe("update:address", data => {
      let url = data.value;
      let datas: Array<string> = url.split("?")[1].split("&");

     // 扫华阳自己的二维码
        if (datas.length == 3) {
            //扫华阳二维码
            // 获取电梯设备Id
            let elevatorId = datas[0].split("=")[1];
            // 获取电梯类型
            let elevatorType = datas[1].split("=")[1];
            let elevatorNum = datas[2].split("=")[1];

            this.geolocation.getCurrentPosition().then(resp => {
                let x = resp.coords.longitude;
                let y = resp.coords.latitude;
                let ggPoint = new window["BMap"].Point(x, y);
                var convertor = new window["BMap"].Convertor();
                var pointArr = [];
                pointArr.push(ggPoint);
                convertor.translate(pointArr, 1, 5, data => {
                    if (data.status === 0) {
                        let param = {
                            lng: data.points[0].lng,
                            lat: data.points[0].lat,
                            id: elevatorId
                        };
                        this.httpService.updateLatLng(param).subscribe(data => {
                            console.log(data);
                        });
                    }
                });
            }).catch(error => {
                alert("获取不到位置信息");
            });

            // 扫描电梯获取设备Id
            this.navCtrl.push(CheckElevator, {
                "elevatorNum": elevatorNum,
                "elevatorType": elevatorType,
                "elevatorId": elevatorId,
                "implementObjectId": this.implementObjectId,
                "scanType": '1',
                "isPassenger": false,
                "planId": this.planId,
                "workType": this.workType
            }).then(() => {
                this.events.unsubscribe("update:address");
                this.navCtrl
                    .getActive()
                    .getNav()
                    .remove(1);
            });
        }else{
            //扫96333二维码
            let devId = url.split("?")[1].split("=")[1];
            this.httpService.findElevatorInfoBy96333({"devId": devId}).subscribe(data => {
                if (data.status == 200) {
                    if (data.data != null) {
                        let elevatorId = data.data.id;
                        let elevatorType = data.data.elevatorTypeId;
                        let elevatorNum = data.data.elevatorNum;
                        this.geolocation.getCurrentPosition().then(resp => {
                            let x = resp.coords.longitude;
                            let y = resp.coords.latitude;
                            let ggPoint = new window["BMap"].Point(x, y);
                            var convertor = new window["BMap"].Convertor();
                            var pointArr = [];
                            pointArr.push(ggPoint);
                            convertor.translate(pointArr, 1, 5, data => {
                                if (data.status === 0) {
                                    let param = {
                                        lng: data.points[0].lng,
                                        lat: data.points[0].lat,
                                        id: elevatorId
                                    };
                                    this.httpService.updateLatLng(param).subscribe(data => {
                                        console.log(data);
                                    });
                                }
                            });
                        }).catch(error => {
                            alert("获取不到位置信息");
                        });

                        // 扫描电梯获取设备Id
                        this.navCtrl.push(CheckElevator, {
                            "elevatorNum": elevatorNum,
                            "elevatorType": elevatorType,
                            "elevatorId": elevatorId,
                            "implementObjectId": this.implementObjectId,
                            "scanType": '1',
                            "isPassenger": false,
                            "planId": this.planId,
                            "workType": this.workType
                        }).then(() => {
                            this.events.unsubscribe("update:address");
                            this.navCtrl
                                .getActive()
                                .getNav()
                                .remove(1);
                        });
                    } else {
                        alert("当前电梯未纳入系统！");
                        return;
                    }
                } else {
                    alert("获取电梯信息失败！");
                    return;
                }
            });
        }
    });
  }

  ionViewWillLeave() {
    this.qrScanner.disableLight();
    this.qrScanner.hide();
    this.qrScanner.destroy();
  }

  ionViewWillEnter() {
      this.qrScanner.prepare().then((status: QRScannerStatus) => {
          if (status.authorized) {
              let sc = this.qrScanner.scan().subscribe((text: string) => {
                  try {
                      sc.unsubscribe();
                      this.qrScanner.pausePreview();
                      this.events.publish("update:address", {
                          value: text
                      });
                  } catch (e) {
                  }
              });
              this.qrScanner.show();
          } else if (status.denied) {
              this.qrScanner.openSettings();
          } else {
          }
      })
          .catch((e: any) => console.log("Error is", e));
  }

  public toggleLight() {
    if (this.lightActive) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.lightActive = !this.lightActive;
  }

  public toggleCamera(): void {
    if (this.cameraToggleActive) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.cameraToggleActive = !this.cameraToggleActive;
  }
}
